package cn.sirun.com.fca.map.view.impl;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.cloud.iov.flow.view.IContentViewContainer;
import com.tencent.cloud.iov.kernel.constant.StatusCode;
import com.tencent.cloud.iov.kernel.model.BaseResponse;
import com.tencent.cloud.iov.router.Router;
import com.tencent.cloud.iov.util.ActivityUtils;
import com.tencent.cloud.iov.util.storage.TXSharedPreferencesUtils;
import com.tencent.cloud.uikit.utils.DialogUtils;
import com.tencent.lbssearch.TencentSearch;
import com.tencent.lbssearch.httpresponse.BaseObject;
import com.tencent.lbssearch.httpresponse.HttpResponseListener;
import com.tencent.lbssearch.object.Location;
import com.tencent.lbssearch.object.param.DrivingParam;
import com.tencent.lbssearch.object.param.Geo2AddressParam;
import com.tencent.lbssearch.object.param.RoutePlanningParam;
import com.tencent.lbssearch.object.param.WalkingParam;
import com.tencent.lbssearch.object.result.DrivingResultObject;
import com.tencent.lbssearch.object.result.Geo2AddressResultObject;
import com.tencent.lbssearch.object.result.RoutePlanningObject;
import com.tencent.lbssearch.object.result.WalkingResultObject;
import com.tencent.tencentmap.mapsdk.maps.CameraUpdate;
import com.tencent.tencentmap.mapsdk.maps.CameraUpdateFactory;
import com.tencent.tencentmap.mapsdk.maps.TencentMap;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptor;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptorFactory;
import com.tencent.tencentmap.mapsdk.maps.model.CameraPosition;
import com.tencent.tencentmap.mapsdk.maps.model.CircleOptions;
import com.tencent.tencentmap.mapsdk.maps.model.LatLng;
import com.tencent.tencentmap.mapsdk.maps.model.Marker;
import com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions;

import java.io.File;
import java.util.List;

import cn.sirun.com.fca.map.R;
import cn.sirun.com.fca.map.constant.MapActivityConst;
import cn.sirun.com.fca.map.model.repose.MapCarLocation;
import cn.sirun.com.fca.map.model.repose.MapCollectedResponse;
import cn.sirun.com.fca.map.model.repose.MapHomeCompanyResponse;
import cn.sirun.com.fca.map.model.request.MapAddCollectedRequest;
import cn.sirun.com.fca.map.model.request.MapSendCarRequest;
import cn.sirun.com.fca.map.presenter.IMapPresenter;
import cn.sirun.com.fca.map.presenter.impl.MapPresenter;
import cn.sirun.com.fca.map.view.IMapCollectedView;
import cn.sirun.com.fca.map.view.impl.MapBaseLoadingFlowView;
import cn.sirun.com.fca.map.widget.MapView;

public class MapSendCarFlowView extends MapBaseLoadingFlowView<IMapPresenter> implements
        IMapCollectedView,View.OnClickListener {

    private MapView mMapView;
    private FrameLayout frameLayout;
    private RelativeLayout relativeLayout;
    private Button button;
    private TextView tvaddress;
    private TextView tvbuild;
    private TextView tvwalktime;
    private TextView tvdrivetime;
    private TextView tv_address;
    private LinearLayout rlTitle;
    private Location[] locations;
    private List<WalkingResultObject.Route> walkRoutes;
    private List<DrivingResultObject.Route> driveRoutes;
    private ImageView iv_collected;
    private Marker marker;
    private TencentMap tencentMap;
    private LatLng LatLng;
    private CameraUpdate cameraSigma;
    private String strlat;
    private String strlng;
    private String title;
    private String address;
    private String flg;
    private Button bt_comfirm;
    private FrameLayout flsendcar;
    private FrameLayout flcomfirm;
    private TextView tv_homeCompany;
    private FrameLayout flmodify;
    private TextView tv_modifyaddress;
    private Button btToModify;
    private Button btToComfirm;
    private Marker mLocationMarker;
    private Marker carMarker;

    private LocationManager locationManager;
    private String locationProvider;
    private LatLng getmLatLng;
    private Marker manMarker;
    private String din;
    private FrameLayout flLocation;
    private ImageView ivLocationGoback;

    private Button btToMap;
    /** 腾讯地图 Uri 标识*/
    public  final static  String BASE_URL = "qqmap://map/";
    private String mantitle;
    private String addressId;

    public MapSendCarFlowView(Activity activity) {
        super(activity);
    }

    public MapSendCarFlowView(Activity activity, IContentViewContainer container) {
        super(activity, container);
    }
    HttpResponseListener directionResponseListener =
            new HttpResponseListener() {

                @Override
                public void onSuccess(int arg0, BaseObject arg1) {
                    // TODO Auto-generated method stub
                    if (arg1 == null) {
                        return;
                    }
                    Log.e("searchdemo", "plan success");
                    RoutePlanningObject obj = (RoutePlanningObject) arg1;
                    Log.e("1111", obj.toString());
                    if (obj instanceof WalkingResultObject) {
                        WalkingResultObject walkObj = (WalkingResultObject) obj;
                        walkRoutes = walkObj.result.routes;
                        tvwalktime.setText(getDuration(walkRoutes.get(0).duration));
                    }
                    if (obj instanceof DrivingResultObject) {
                        DrivingResultObject drivingObj = (DrivingResultObject) obj;
                        driveRoutes = drivingObj.result.routes;
                        tvdrivetime.setText(getDuration(driveRoutes.get(0).duration));
                    }
                }

                @Override
                public void onFailure(int arg0, String arg1, Throwable arg2) {
                    // TODO Auto-generated method stub
                    Toast.makeText(getActivity(), arg1, Toast.LENGTH_SHORT).show();
                }
            };
    @Override
    public void onCreate() {
        super.onCreate();
        View view = LayoutInflater.from(getContext())
                .inflate(R.layout.map_send_address_to_car, null, false);
        setContentView(view);
        mMapView = view.findViewById(R.id.map);
        tencentMap = mMapView.getMap();

        flsendcar= view.findViewById(R.id.fl_send_car);
        flcomfirm = view.findViewById(R.id.fl_comfirm_address);
        flmodify = view.findViewById(R.id.fl_modify_address);
        //发送到车对话框
        frameLayout = view.findViewById(R.id.fl_sendcar_dialog);
        relativeLayout = view.findViewById(R.id.rl_send_to_car);
        relativeLayout.setOnClickListener(this);
        button = view.findViewById(R.id.bt_send_dialog_close);
        button.setOnClickListener(this);
        btToMap = view.findViewById(R.id.bt_daohang);
        btToMap.setOnClickListener(this);
        //点击搜索跳转
        tv_address = view.findViewById(R.id.map_search);
        rlTitle = view.findViewById(R.id.ll_send_search);
        rlTitle.setOnClickListener(this);
        //行程框
        tvaddress = view.findViewById(R.id.tv_map_line_name);
        tvbuild = view.findViewById(R.id.tv_map_address_name);
        tvwalktime = view.findViewById(R.id.tv_map_walk_time);
        tvdrivetime = view.findViewById(R.id.tv_map_drive_time);
        //收藏
        iv_collected = view.findViewById(R.id.iv_map_collect);
        iv_collected.setOnClickListener(this);
        //设置地址
        tv_homeCompany = view.findViewById(R.id.tv_map_company_address);
        bt_comfirm = view.findViewById(R.id.bt_comfirm_address);
        bt_comfirm.setOnClickListener(this);
        tv_modifyaddress = view.findViewById(R.id.tv_map_modify_company_address);
        btToComfirm = view.findViewById(R.id.bt_to_comfirm_address);
        btToComfirm.setOnClickListener(this);
        btToModify = view.findViewById(R.id.bt_to_modify);
        btToModify.setOnClickListener(this);
        //开启地位
        flLocation =view.findViewById(R.id.fl_location_error);
        ivLocationGoback = view.findViewById(R.id.iv_location_error_goback);
        ivLocationGoback.setOnClickListener(this);

        din=TXSharedPreferencesUtils.getValue("car_activate_info");
        if(din!=null){
//            getPresenter().getLastLocation(din);
            getPresenter().updateLocation(din);
        }else {
            getPresenter().updateLocation("");
        }
        // 获取意图对象获取传递的值
        Intent intent = getActivity().getIntent();
         strlat = intent.getStringExtra("addresslat");
         strlng = intent.getStringExtra("addresslng");
         title = intent.getStringExtra("title");
         address = intent.getStringExtra("address");

         addressId = intent.getStringExtra("favoritesId");
         if(addressId!=null){
             iv_collected.setImageResource(R.drawable.collected_star);
         }
        if(title.equals("man")){
            //地址信息
            reGeocoder(strlat, strlng);
        }else {
            tvbuild.setText(title);
            tvaddress.setText(address);
            tv_address.setText(title);
        }
        //判断设置还是发送
        flg = intent.getStringExtra("set");
        if(flg.equals("sethome")){
            flcomfirm.setVisibility(View.VISIBLE);
            flsendcar.setVisibility(View.GONE);
            tv_homeCompany.setText(title);
            setMarker(strlat, strlng,"");
        }else if(flg.equals("setcompany")){
            flcomfirm.setVisibility(View.VISIBLE);
            flsendcar.setVisibility(View.GONE);
            tv_homeCompany.setText(title);
            setMarker(strlat, strlng,"");
        }if(flg.equals("send")){
            flcomfirm.setVisibility(View.GONE);
            flsendcar.setVisibility(View.VISIBLE);
            locations = getCoords("39.90","116.38",strlat,strlng);
            //构建Marker图标
            BitmapDescriptor bitmap = BitmapDescriptorFactory
                    .fromResource(R.drawable.car_marker);
            carMarker = tencentMap.addMarker(new MarkerOptions().
                    position(new LatLng(39.9,116.38)).
                    icon(bitmap).
                    draggable(true));
            // 目的地
            setMarker(strlat, strlng,"");
            //步行开车时间
            getWalkPlan();
            getDrivePlan();

        }if(flg.equals("modifyhome")){
            tv_modifyaddress.setText(title);
            flmodify.setVisibility(View.VISIBLE);
            flsendcar.setVisibility(View.GONE);
            setMarker(strlat, strlng,"");
        }if(flg.equals("modifycompany")){
            tv_modifyaddress.setText(title);
            flmodify.setVisibility(View.VISIBLE);
            flsendcar.setVisibility(View.GONE);
            setMarker(strlat, strlng,"");
        }
    }

    protected void setMarker(String slat, String slng,String set) {
        if(marker!=null){
            marker.remove();
        }
        if(flg.contains("comfirm")){
            if(isLocServiceEnable(getActivity())){
                startLocation();
            }else {
                DialogUtils.showToast(getActivity(),"请开启手机定位！");
            }
        }else if(flg.equals("send")){
            if(manMarker!=null){
                manMarker.remove();
            }
        }

        //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.add_marker);
        LatLng = new LatLng(Double.parseDouble(slat), Double.parseDouble(slng));
        marker = tencentMap.addMarker(new MarkerOptions()
                .position(LatLng)
                .draggable(true)
                .icon(bitmap)
                .draggable(true));

        //地图中心设置
        cameraSigma = CameraUpdateFactory.newCameraPosition(new CameraPosition(
                new LatLng(Double.parseDouble(slat), Double.parseDouble(slng)), //新的中心点坐标
                9,  //新的缩放级别
                0, //俯仰角 0~45° (垂直地图时为0)
                0)); //偏航角 0~360° (正北方为0)
        tencentMap.moveCamera(cameraSigma);

        tencentMap.setOnMarkerClickListener(new TencentMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker mker) {
                if(mker==carMarker){
                    carMarker.showInfoWindow();
                }else if(mker==marker){
                    marker.showInfoWindow();
                }else if(mker==manMarker){
                    manMarker.showInfoWindow();
                }
                return false;
            }
        });

    }

    protected Location[] getCoords(String carlat,String carlng,String deslat,String deslng) {
        Location start = new Location(Float.parseFloat(carlat), Float.parseFloat(carlng));
        Location destination = new Location(Float.parseFloat(deslat), Float.parseFloat(deslng));
        Location[] locations = {start, destination};
        return locations;
    }

    /**
     * 步行规划，只能设置起点和终点
     */
    protected void getWalkPlan() {
        TencentSearch tencentSearch = new TencentSearch(getContext());
        WalkingParam walkingParam = new WalkingParam();
        walkingParam.from(locations[0]);
        walkingParam.to(locations[1]);
        tencentSearch.getDirection(walkingParam, directionResponseListener);
    }

    /**
     * 驾车规划，支持途经点和策略设置，具体信息见文档
     */
    protected void getDrivePlan() {
        TencentSearch tencentSearch = new TencentSearch(getContext());
        DrivingParam drivingParam = new DrivingParam();
        drivingParam.from(locations[0]);
        drivingParam.to(locations[1]);
        //策略
        drivingParam.policy(RoutePlanningParam.DrivingPolicy.LEAST_DISTANCE);
        //途经点
//		drivingParam.addWayPoint(new Location(39.898938f, 116.348648f));
        tencentSearch.getDirection(drivingParam, directionResponseListener);
    }

    /**
     * 将时间转换成小时+分钟
     *
     * @param duration
     * @return
     */
    protected String getDuration(float duration) {
//        if (duration < 60) {
//            return Integer.toString((int) duration) + "min";
//        } else {
//            return Integer.toString((int) (duration / 60)) + "h"
//                    + Integer.toString((int) (duration % 60)) + "min";
//        }
        return Integer.toString((int) duration) + "min";
    }

    /**
     * 逆地理编码
     */
    protected void reGeocoder(String lat,String lng) {
//        str = "39.90,116.38";
        String str = lat+","+lng;
        Location location = str2Coordinate(getContext(), str);
        if (location == null) {
            return;
        }
        TencentSearch tencentSearch = new TencentSearch(getContext());
        //还可以传入其他坐标系的坐标，不过需要用coord_type()指明所用类型
        //这里设置返回周边poi列表，可以在一定程度上满足用户获取指定坐标周边poi的需求
        Geo2AddressParam geo2AddressParam = new Geo2AddressParam().
                location(location).get_poi(true);
        tencentSearch.geo2address(geo2AddressParam, new HttpResponseListener() {

            @Override
            public void onSuccess(int arg0, BaseObject arg1) {
                // TODO Auto-generated method stub
                if (arg1 == null) {
                    return;
                }
                Geo2AddressResultObject obj = (Geo2AddressResultObject) arg1;
//                StringBuilder sb = new StringBuilder();
//                sb.append(obj.result.address);
                mantitle=obj.result.formatted_addresses.recommend;
                tvaddress.setText(obj.result.address);
                tvbuild.setText(obj.result.formatted_addresses.recommend);
                tv_address.setText(obj.result.formatted_addresses.recommend);
                if(flg.equals("modifyhome")){
                    if(!TextUtils.isEmpty(din)) {
                        showLoadingView();
                        getPresenter().addCollectAddress(din, new MapAddCollectedRequest
                                (manMarker.getPosition().longitude+"",manMarker.getPosition().latitude+"",  obj.result.formatted_addresses.recommend, "1",obj.result.address ));
                    }else {
                        showLoadingView();
                        getPresenter().addCollectAddress("", new MapAddCollectedRequest
                                (manMarker.getPosition().longitude+"",manMarker.getPosition().latitude+"",  obj.result.formatted_addresses.recommend, "1",obj.result.address ));
                    }
                }else if(flg.equals("modifycompany")){
                    if(!TextUtils.isEmpty(din)) {
                        showLoadingView();
                        getPresenter().addCollectAddress(din, new MapAddCollectedRequest
                                ( manMarker.getPosition().longitude+"",manMarker.getPosition().latitude+"", obj.result.formatted_addresses.recommend, "2", obj.result.address));
                    }else {
                        showLoadingView();
                        getPresenter().addCollectAddress("", new MapAddCollectedRequest
                                ( manMarker.getPosition().longitude+"",manMarker.getPosition().latitude+"", obj.result.formatted_addresses.recommend, "2", obj.result.address));
                    }

                }

            }

            @Override
            public void onFailure(int arg0, String arg1, Throwable arg2) {
                // TODO Auto-generated method stub
//                printResult(arg1);
            }
        });
    }

    /**
     * 由字符串获取坐标
     *
     * @param context
     * @param str
     * @return
     */
    public static Location str2Coordinate(Context context, String str) {
        if (!str.contains(",")) {
            Toast.makeText(context, "经纬度用\",\"分割", Toast.LENGTH_SHORT).show();
            return null;
        }
        String[] strs = str.split(",");
        float lat = 0;
        float lng = 0;
        try {
            lat = Float.parseFloat(strs[0]);
            lng = Float.parseFloat(strs[1]);
        } catch (NumberFormatException e) {
            Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
            return null;
        }
        return new Location(lat, lng);
    }


    LocationListener locationListener = new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status, Bundle arg2) {

        }

        @Override
        public void onProviderEnabled(String provider) {
//            Log.d(TAG, "onProviderEnabled: " + provider + ".." + Thread.currentThread().getName
// ());
        }

        @Override
        public void onProviderDisabled(String provider) {
//            Log.d(TAG, "onProviderDisabled: " + provider + ".." + Thread.currentThread()
// .getName());
        }

        @Override
        public void onLocationChanged(android.location.Location location) {
            //如果位置发生变化,重新显示
            if(!flg.equals("send")){
                showLocation(location);
            }
        }
    };

    private void showLocation(android.location.Location location) {
        //构建Marker图标

        if(!flg.equals("send")){
            BitmapDescriptor bitmap = BitmapDescriptorFactory
                    .fromResource(R.drawable.man_marker);
            getmLatLng = new LatLng(location.getLatitude(), location.getLongitude());
            manMarker = tencentMap.addMarker(new MarkerOptions()
                    .icon(bitmap)
                    .position(getmLatLng)
                    .draggable(true));
        }

//        Log.d(TAG,"定位成功------->"+"location------>经度为：" + location.getLatitude() + "\n纬度为" +
// location.getLongitude());
    }
    @Override
    public void onStart() {
        super.onStart();
        mMapView.onStart();
        if(flg.contains("modify")){
            if(isLocServiceEnable(getActivity())){
                startLocation();
            }else{
                flLocation.setVisibility(View.VISIBLE);
            }
        }
        din=TXSharedPreferencesUtils.getValue("car_activate_info");
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        mMapView.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    protected IMapPresenter createPresenter() {
        return new MapPresenter();
    }

    @Override
    public void getMapCollected(BaseResponse<MapCollectedResponse> response) {

    }

    @Override
    public void addMapCollected(BaseResponse<BaseResponse> response) {
            hideLoadingView();
        DialogUtils.showToast(getActivity(),response.getMsg());
        if(response.getCode()==0){
            iv_collected.setImageResource(R.drawable.collected_star);
        }
    }

    @Override
    public void deleteMapCollected(BaseResponse<BaseResponse> response) {
        hideLoadingView();
        DialogUtils.showToast(getActivity(),response.getMsg());
        if(response.getCode()==0){
            iv_collected.setImageResource(R.drawable.collect_star);
            addressId=null;
        }
    }

    @Override
    public void mapHomeCompany(BaseResponse<MapHomeCompanyResponse> response) {

    }

    @Override
    public void mapSendToCar(BaseResponse<MapHomeCompanyResponse> response) {
        frameLayout.setVisibility(View.GONE);
        DialogUtils.showToast(getActivity(),response.getMsg());
    }

    @Override
    public void getLastLocation(BaseResponse<MapCarLocation> response) {

    }

    @Override
    public void updateLocation(BaseResponse<MapCarLocation> response) {

    }

    public static boolean isInstalled() {
        return new File("/data/data/com.tencent.map").exists();
    }

    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.rl_send_to_car){
            if(!TextUtils.isEmpty(din)) {
                getPresenter().mapSendToCar(din, new MapSendCarRequest(title, strlat, strlng));
            }else {
                getPresenter().mapSendToCar("", new MapSendCarRequest(title, strlat, strlng));
            }
            frameLayout.setVisibility(View.VISIBLE);
        }else if(v.getId()==R.id.bt_send_dialog_close){
            frameLayout.setVisibility(View.GONE);
        }else if(v.getId()==R.id.bt_daohang){
                if (isInstalled()){
                    if(title.equals("man")&&!TextUtils.isEmpty(mantitle)){
                        invokeNavi(getActivity(),"drive",null,null,null,mantitle,strlat+","+strlng,null,"textApp");
                    }else {
                        invokeNavi(getActivity(),"drive",null,null,null,title,strlat+","+strlng,null,"textApp");
                    }
                }else {
                    DialogUtils.showToast(getActivity(),"尚未安装腾讯地图,请先下载安装");
                }
        }else if(v.getId()==R.id.ll_send_search){
            Intent intent = Router.fromPath(MapActivityConst.Path.MAP_SEARCH);
            ActivityUtils.startActivity(getActivity(),intent);
            getActivity().finish();
        }else if(v.getId()==R.id.iv_map_collect){
            if(!TextUtils.isEmpty(din)){
                if (addressId!=null) {
                    getPresenter().deleteCollectAddress(din, addressId);
                    showLoadingView();
                }else{
                    getPresenter().addCollectAddress(din, new MapAddCollectedRequest
                            (strlng, strlat, title, "0", address));
                    showLoadingView();
                }
            }else {
                if (addressId!=null) {
                    getPresenter().deleteCollectAddress("", addressId);
                    showLoadingView();
                }else{
                    getPresenter().addCollectAddress("", new MapAddCollectedRequest
                            (strlng, strlat, title, "0", address));
                    showLoadingView();
                }
            }

        }else if(v.getId()==R.id.bt_comfirm_address){
            if(flg.equals("sethome")){
                if(!TextUtils.isEmpty(din)) {
                    getPresenter().addCollectAddress(din, new MapAddCollectedRequest
                            (strlng, strlat, title, "1", address));
                    showLoadingView();
                }else {
                    getPresenter().addCollectAddress("", new MapAddCollectedRequest
                            (strlng, strlat, title, "1", address));
                    showLoadingView();
                }
            }else if(flg.equals("setcompany")){
                if(!TextUtils.isEmpty(din)) {
                    getPresenter().addCollectAddress(din, new MapAddCollectedRequest
                            ( strlng, strlat,title, "2", address));
                    showLoadingView();
                }else {
                    getPresenter().addCollectAddress("", new MapAddCollectedRequest
                            ( strlng, strlat,title, "2", address));
                    showLoadingView();
                }
            }
        }else if(v.getId()==R.id.bt_to_comfirm_address){
            if(flg.equals("modifyhome")){
                if(manMarker!=null){
                    setMarker(manMarker.getPosition().latitude+"",manMarker.getPosition().longitude+"","comfirm");
                    reGeocoder(manMarker.getPosition().latitude+"", manMarker.getPosition().longitude+"");
                }

            }else if(flg.equals("modifycompany")){
                if(manMarker!=null){
                    setMarker(manMarker.getPosition().latitude+"",manMarker.getPosition().longitude+"","comfirm");
                    reGeocoder(manMarker.getPosition().latitude+"", manMarker.getPosition().longitude+"");
                }
            }
        }else if(v.getId()==R.id.bt_to_modify){
            if(flg.equals("modifyhome")){
                Intent intent = Router.fromPath(MapActivityConst.Path.MAP_SEARCH);
                intent.putExtra("set","modifyhome");
                ActivityUtils.startActivity(getActivity(),intent);

            }else if(flg.equals("modifycompany")){
                Intent intent = Router.fromPath(MapActivityConst.Path.MAP_SEARCH);
                intent.putExtra("set","modifycompany");
                ActivityUtils.startActivity(getActivity(),intent);
            }

        }else if(v.getId()==R.id.iv_location_error_goback){
            getActivity().finish();
        }
    }

    public static  void invokeNavi(Context context, String type,String coord_type, String from ,
                                   String fromcoord, String to, String tocoord,String policy,String referer){
        StringBuffer stringBuffer  = new StringBuffer(BASE_URL)
                .append("routeplan?")
                .append("type=")
                .append(type)
                .append("&to=")
                .append(to)
                .append("&tocoord=")
                .append(tocoord)
                .append("&referer=")
                .append(referer);
        if (!TextUtils.isEmpty(from)){
            stringBuffer.append("&from=").append(from);
        }
        if (!TextUtils.isEmpty(fromcoord)){
            stringBuffer.append("&fromcoord=").append(fromcoord);
        }
        if (!TextUtils.isEmpty(policy)){
            stringBuffer .append("&policy=").append(policy);
        }
        if (!TextUtils.isEmpty(coord_type)){
            stringBuffer .append("&coord_type=").append(coord_type);
        }
        Intent intent = new Intent();
        intent.setData(Uri.parse(stringBuffer.toString()));
        context.startActivity(intent);
    }

    private void startLocation() {
//        TencentLocationRequest request = TencentLocationRequest.create();
//        request.setInterval(5000);
//        mLocationManager.requestLocationUpdates(request, this);
        locationManager = (LocationManager) getActivity().getSystemService(getContext()
                .LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);//低精度，如果设置为高精度，依然获取不了location。
        criteria.setAltitudeRequired(false);//不要求海拔
        criteria.setBearingRequired(false);//不要求方位
        criteria.setCostAllowed(true);//允许有花费
        criteria.setPowerRequirement(Criteria.POWER_LOW);//低功耗
        locationProvider = locationManager.getBestProvider(criteria, true);
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission
                .ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission
                .ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        android.location.Location location = locationManager.getLastKnownLocation(locationProvider);
        if (!flg.equals("send")) {
            //不为空,显示地理位置经纬度
            showLocation(location);
        }
        //监视地理位置变化
        locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);
    }

    /**
     * 手机是否开启位置服务，如果没有开启那么所有app将不能使用定位功能
     */
    public static boolean isLocServiceEnable(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }
}
